#!/usr/bin/env python3
from json import loads
from pprint import pprint
from collections import defaultdict
from datetime import datetime
from os.path import join,dirname,basename
from pathlib import Path
#  pigz -dc 668897.json.gz|rg "02426ddc0406df4e|991e49cf8e79a18b|fe7baa7284685eba|b0738e00867f8a85|6cf6292ce097764f|8a4bb551474298cd|8909079462f6b329|339d2c96124018e|e4fd1ad1bbc469c8|88ebb2ee9675d6b9|f87fc330b6027da1|407bcd6089ad09b7|59eb3eca95ec4c9f|01bfaf42ce678c9c|fbf47e66a534b1d9|c15f20358a678c8f|4f8a9e4f8ad9041c|635670ecb9dd8885|f4c713ee89621c2b|46b7188f6ff05744|20d75195e1aafcf1|019cb5324cf3eb6d|f734759724e105cb|acf3a67e31adfb9f|6c2714bbb098b410|7a0500894a9ec7ee|542bf2d43dd87377|69c5cec6e5809dc9|a2b6ccbc356f0320|3f3da5b54d8a47c4|d61a91c44201e81b|2b4bb8f933670cf5|54ce2e5fdd357862|26d071dd3972811a|b3d97078ecf8c270|e4ed58cd74886291|347c1a2da5c209f4|ce81ee83404ce174|7818200c95166bbd|659518a9d7b62bc4|888a382f482944bf|4e1d27391abe6179|8d88bd8ac539cfd6|7375cc24ba54f5cd|4a4caa84bc1c0ab8|026f60a726e248f7|f57dd101eededb9|5f2870cd99bdecc2" > 668897

OUTDIR = "/root/user"


def user_action_log(filepath):
  user_action = defaultdict(list)
  user_meta = {}
  with open(filepath) as infile:
    for i in infile:
      i = loads(i)
      e = i['eventParameters']
      sessionTimestamp = int(i['sessionTimestamp']) // 1000
      id = i['deviceIdentifiers']['AndroidId']
      page_name = e.get('voip_call', 0) or e.get(
        'page_name', ''
      ) or e.get('send_message') or e.get('update_click'
                                          ) or i.get('eventName')
      # if not page_name:
      #   print(i)
      if id not in user_action:
        user_meta[id] = ("system", e.get("systemVersion&systemModel",""))
      user_id = i.get('eventParameters',{}).get("userId","")
      user_action[id].append((sessionTimestamp, page_name,user_id))

  outdir = join(OUTDIR,basename(dirname(filepath)))
  print(outdir)
  Path(outdir).mkdir(parents=True, exist_ok=True)
  for uid, li in user_action.items():
    li.sort(key=lambda x: x[0])
    with open(f"{outdir}/{uid}.csv", "w") as out:
      out.write(f",\n{','.join(user_meta[uid])}\n")
      out.write("time,action,user_id\n")
      for ts, page,user_id in li:
        out.write(f"{datetime.fromtimestamp(ts)},{page},{user_id}\n")


if __name__ == "__main__":
  from fire import Fire
  Fire(user_action_log)


